﻿package com.framewrok.core.poi.util.office;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public abstract class ExcelGenerateUtil extends ExcelUtil {

	/**
	 * 
	 * @param pth
	 * @param xwb
	 * @throws IOException
	 */
	public static void write(String pth, Workbook xwb) throws IOException {
		OutputStream os = null;
		try {
			os = new FileOutputStream(pth);
			xwb.write(os);
			os.close();
			os = null;
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (Exception e) {

				}
			}
		}

	}

	/**
	 * excel 替换相关的所有数据。
	 * 
	 * @param tmpPth
	 *            模板文件
	 * @param genPth
	 *            生成文件路径
	 * @param map
	 *            替换值
	 * @throws IOException
	 */
	public static void replaceData(String tmpPth, String genPth, Map<String, Object> data) throws IOException {
		Workbook book = read(tmpPth);
		Iterator<Sheet> it = book.sheetIterator();
		Sheet sheet = null;
		Row row = null;
		int firstCol = 0;
		int lastCol = 0;
		int rowfirst = 0;
		int rowlast = 0;
		Cell cell = null;
		while (it.hasNext()) {
			sheet = it.next();
			rowfirst = sheet.getFirstRowNum();
			rowlast = sheet.getLastRowNum();
			for (int i = rowfirst; i <= rowlast; i++) {
				row = sheet.getRow(i);
				if (row == null)
					continue;
				firstCol = row.getFirstCellNum();
				lastCol = row.getLastCellNum();
				for (int j = firstCol; j <= lastCol; j++) {
					cell = row.getCell(j);
					cell.getArrayFormulaRange();

				}

			}
		}
		write(genPth, book);
	}

	public static String readCellValue(Sheet sheet, int rown, int celln) {
		Cell cell = sheet.getRow(rown).getCell(celln);
		return read(cell);
	}

}
